package com.fstec.ks.master.netty;

import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.socket.SocketChannel;
import io.netty.handler.ssl.SslContext;
import io.netty.handler.ssl.SslContextBuilder;
import io.netty.handler.ssl.util.SelfSignedCertificate;
import io.netty.handler.timeout.IdleStateHandler;

import java.util.List;

import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;

import com.fstec.ks.master.MasterEngine;
import com.sinotn.SinotnLogger;

public class ExamInitializer extends ChannelInitializer<SocketChannel> implements InitializingBean {
	@Autowired
	private MasterEngine masterEngine;
	private List<ChannelHandler> sharableHandlers;
	private boolean ssl=false;
	private int idleSeconds=0;
	private SslContext sslCtx;

	public ExamInitializer(){}

	public void setSsl(boolean ssl) {
		this.ssl = ssl;
	}

	public void setIdleSeconds(int idleSeconds) {
		this.idleSeconds = idleSeconds;
	}

	public void setSharableHandlers(List<ChannelHandler> sharableHandlers) {
		this.sharableHandlers = sharableHandlers;
	}

	@Override
	protected void initChannel(SocketChannel ch) throws Exception {
		ChannelPipeline p = ch.pipeline();
		if (sslCtx != null) {
			p.addLast(sslCtx.newHandler(ch.alloc()));
		}
		if(null!=this.sharableHandlers){
			int size=this.sharableHandlers.size();
			for(int i=0;i<size;i++){
				p.addLast(this.sharableHandlers.get(i));
			}
		}
		if(SinotnLogger.DEBUG.isDebugEnabled()){
			SinotnLogger.DEBUG.debug("初始化Socket Channel @"+p.channel().id().asShortText());
		}
		if(this.idleSeconds>0){
			// readIdleSeconds秒没有读数据断开连接
			p.addLast(new IdleStateHandler(0, 0, this.idleSeconds));
		}
		p.addLast(new MessageHandler(this.masterEngine));
	}

	@Override
	public void afterPropertiesSet() throws Exception {
		if(this.ssl){
			SelfSignedCertificate ssc = new SelfSignedCertificate();
			this.sslCtx = SslContextBuilder.forServer(ssc.certificate(), ssc.privateKey()).build();
		}
	}
}
